package com.zut.base.common.config;

import com.zut.base.common.entry.ResultCode;
import com.zut.base.common.entry.ResultVO;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.Set;

/** 全局异常处理类
 * @author zhang
 * @date 2020/11/4 13:55
 */
@RestControllerAdvice
public class AllExceptionHandler {

    //API响应异常处理
    @ExceptionHandler(APIException.class)
    public ResultVO<String> APIExceptionHandler(APIException e) {
        //返回类型是自定义响应体
        return new ResultVO<String>(e.getCode(), e.getMsg(),null);
    }

    //参数检验异常处理
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResultVO<String> MethodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) {
        // 从异常对象中拿到ObjectError对象
        ObjectError objectError = e.getBindingResult().getAllErrors().get(0);
        // 然后提取错误提示信息进行返回
        return new ResultVO<String>(ResultCode.VALIDATE_FAILED,objectError.getDefaultMessage());
    }

    //参数检验异常处理
    @ExceptionHandler(ConstraintViolationException.class)
    public  ResultVO<String> resolveConstraintViolationException(ConstraintViolationException ex){
        ResultVO<String> result = new ResultVO<String>();
        Set<ConstraintViolation<?>> constraintViolations = ex.getConstraintViolations();
        if(!CollectionUtils.isEmpty(constraintViolations)){
            StringBuilder msgBuilder = new StringBuilder();
            for(ConstraintViolation constraintViolation :constraintViolations){
                msgBuilder.append(constraintViolation.getMessage()).append(",");
            }
            String errorMessage = msgBuilder.toString();
            if(errorMessage.length()>1){
                errorMessage = errorMessage.substring(0,errorMessage.length()-1);
            }
            result.set(ResultCode.VALIDATE_FAILED,errorMessage);
            return result;
        }
        result.set(ResultCode.VALIDATE_FAILED,ex.getMessage());
        return result;
    }

    @ExceptionHandler(Exception.class)
    public ResultVO<String> APIExceptionHandler(Exception e) {
        e.printStackTrace();
        //返回类型是自定义响应体
        return new ResultVO<String>(500, "系统异常",null);
    }
}
